﻿using System;
using System.Globalization;
using System.Threading.Tasks;
using Casamiel.API.Application;
using Casamiel.API.Application.Services;
using Casamiel.Application;
//using Microsoft.AspNetCore.Http.Internal;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;
using Newtonsoft.Json;
using NLog;
using PaySharp.Core;

namespace Casamiel.Controllers
{
    /// <summary>
    /// 
    /// </summary>
    /// 
    //[ApiVersion("1.0")]
    [ApiVersionNeutral]
    public class NotifyController : Controller
    {
        //private readonly IGateways gateways;
        private readonly IPaymentService _paymentService;
        private readonly IIcApiService _iicApiService;
        private readonly IUserLogService _userLog;
        private readonly IAllPayService _allPayService;
        private readonly NLog.ILogger logger = LogManager.GetLogger("PayService");

        /// <summary>
        /// Gets the configuration.
        /// </summary>
        /// <value>The configuration.</value>
        public IConfiguration Configuration { get; }

        /// <summary>
        /// Initializes a new instance  class.
        /// </summary>
        /// <param name="configuration">Gateways.</param>
        /// <param name="paymentRecord">Payment record.</param>
        /// <param name="userLog">User log.</param>
        /// <param name="iicApiService">Iic API service.</param>
        /// <param name="allPayService">All pay service.</param>
        public NotifyController(IConfiguration configuration,
            IPaymentService paymentRecord,
            IUserLogService userLog,
                                IIcApiService iicApiService, IAllPayService allPayService)
        {
            this.Configuration = configuration;
            _paymentService = paymentRecord;
            _userLog = userLog;
            _iicApiService = iicApiService;
            this._allPayService = allPayService;

        }
        /// <summary>
        /// 
        /// </summary>
        /// <returns></returns>
        public async Task Index()
        {
            //Request.EnableRewind();
            // 订阅支付通知事件
            var Alipaymerchant = new PaySharp.Alipay.Merchant() {
                AppId = Configuration.GetSection("AlipaySettings").GetValue<string>("AppId"),// "2018012302035911",
                NotifyUrl = Configuration.GetSection("AlipaySettings").GetValue<string>("NotifyUrl"),//"http://xiaoha.zicp.net:10154/Notify",//
                ReturnUrl = Configuration.GetSection("AlipaySettings").GetValue<string>("ReturnUrl"),//"http://xiaoha.zicp.net:10154/Notify1",//
                AlipayPublicKey = Configuration.GetSection("AlipaySettings").GetValue<string>("AlipayPublicKey"),
                Privatekey = Configuration.GetSection("AlipaySettings").GetValue<string>("Privatekey")
            };
            PaySharp.Alipay.AlipayGateway alipayGateway = new PaySharp.Alipay.AlipayGateway(Alipaymerchant);

            var wechatpayMerchant = new PaySharp.Wechatpay.Merchant {
                AppId = Configuration.GetSection("WxPaySettigs").GetValue<string>("AppId"),//"wxbecc5bd1b44d6419",
                MchId = Configuration.GetSection("WxPaySettigs").GetValue<string>("MchId"),// "1495718342",//1233410002",
                Key = Configuration.GetSection("WxPaySettigs").GetValue<string>("Key"),//"10adc3849ba6abe56e056f20f83e71dA",
                AppSecret = Configuration.GetSection("WxPaySettigs").GetValue<string>("AppSecret"),// "e82319affef9caa8fe91e793c4c1507d",
                SslCertPath = Configuration.GetSection("WxPaySettigs").GetValue<string>("SslCertPath"),//"Certs/apiclient_cert.p12",
                SslCertPassword = Configuration.GetSection("WxPaySettigs").GetValue<string>("SslCertPassword"),// "1233410002",
                NotifyUrl = Configuration.GetSection("WxPaySettigs").GetValue<string>("NotifyUrl"),// Configuration.GetValue<string>("wxpayNotifyUrl"),// "http://localhost:61337/Notify"

            };
            PaySharp.Wechatpay.WechatpayGateway ga = new PaySharp.Wechatpay.WechatpayGateway(wechatpayMerchant);
            IGateways gateways = new Gateways();
            gateways.Add(alipayGateway);
            gateways.Add(ga);

            Notify notify = new Notify(gateways);
            notify.PaySucceed += Notify_PaySucceed;
            notify.RefundSucceed += Notify_RefundSucceed;
            notify.UnknownNotify += Notify_UnknownNotify;
            notify.UnknownGateway += Notify_UnknownGateway;

            // 接收并处理支付通知
            await notify.ReceivedAsync().ConfigureAwait(false);
        }
        private bool Notify_RefundSucceed(object arg1, RefundSucceedEventArgs arg2)
        {
            logger.Trace("Notify_RefundSucceed:" + JsonConvert.SerializeObject(arg2));

            //if(arg2.GatewayType==typeof(PaySharp.Alipay.AlipayGateway))
            //{
            //    var a = (PaySharp.Alipay.Response.RefundResponse)arg2.NotifyResponse;
            //    logger.Error($"{JsonConvert.SerializeObject(a)}");

            //}
            // 订单退款时的处理代码
            return true;
        }
        private bool Notify_UnknownNotify(object sender, UnKnownNotifyEventArgs e)
        {
            logger.Error("Notify_PaymentFailed:" + JsonConvert.SerializeObject(e));
            // 未知时的处理代码
            return false;
        }
        private bool Notify_PaySucceed(object sender, PaySucceedEventArgs e)
        {
            // 支付成功时时的处理代码
            /* 建议添加以下校验。
             * 1、需要验证该通知数据中的OutTradeNo是否为商户系统中创建的订单号，
             * 2、判断Amount是否确实为该订单的实际金额（即商户订单创建时的金额），
             */
            if (e.GatewayType == typeof(PaySharp.Alipay.AlipayGateway)) {
                var alipayNotify = (PaySharp.Alipay.Response.NotifyResponse)e.NotifyResponse;
                Console.WriteLine($"OutTradeNo：{alipayNotify.OutTradeNo},TradeNo：{alipayNotify.TradeNo}");
                logger.Trace(JsonConvert.SerializeObject(alipayNotify));
                var s = _allPayService.PayComplete(alipayNotify.OutTradeNo, alipayNotify.TradeNo, alipayNotify.TotalAmount, alipayNotify.AppId);
                s.Wait();
                return s.GetAwaiter().GetResult();
            }
            if (e.GatewayType == typeof(PaySharp.Wechatpay.WechatpayGateway)) {
                var wechatpayNotify = (PaySharp.Wechatpay.Response.NotifyResponse)e.NotifyResponse;

                Console.WriteLine($"OutTradeNo：{wechatpayNotify.OutTradeNo},TradeNo：{wechatpayNotify.TradeNo},{wechatpayNotify.TotalAmount},{wechatpayNotify.MchId},{DateTime.Now.ToString("yyyyMMdd HH:mm:ss.fff", CultureInfo.CurrentCulture)}");
                logger.Trace(JsonConvert.SerializeObject(wechatpayNotify));
                var s = _allPayService.PayComplete(wechatpayNotify.OutTradeNo, wechatpayNotify.TradeNo, wechatpayNotify.TotalAmount / 100, wechatpayNotify.MchId);
                s.Wait();
                return s.GetAwaiter().GetResult();

                //同步通知，即浏览器跳转返回
            }
            //处理成功返回true
            return false;
        }

        //private void Notify_PaymentFailed(object sender, PayFailedEventArgs e)
        //{
        //    logger.Error("Notify_PaymentFailed:" + JsonConvert.SerializeObject(e));
        //    // 支付失败时的处理代码
        //    //if (e.GatewayType == typeof(ICanPay.Alipay.AlipayGateway))
        //    //{
        //    //    var alipayNotify = (ICanPay.Alipay.Notify)e.Notify;
        //    //    if (alipayNotify.TradeStatus == "TRADE_CLOSED")
        //    //    {

        //    //    }
        //    //}
        //}

        private void Notify_UnknownGateway(object sender, UnknownGatewayEventArgs e)
        {
            // 无法识别支付网关时的处理代码
        }
    }
}
